from langchain_core.tools import tool
from home.models import Jobposting


@tool(description="职位检索：传入关键词(岗位/标签/城市关键字)，直接返回前10条职位明细(JSON)。若无匹配则返回全站热门前10条。")
def JobSearch(keyword: str) -> str:
    qs = Jobposting.objects.select_related("company", "city").all()
    if keyword:
        qs = qs.filter(title__icontains=keyword) | qs.filter(label__icontains=keyword) | qs.filter(company__name__icontains=keyword)
    qs = qs.order_by("-browse_number")[:10]
    if not qs:
        # 无匹配时回退热门Top10
        qs = Jobposting.objects.select_related("company", "city").all().order_by("-browse_number")[:10]
    items = []
    for j in qs:
        items.append({
            "title": j.title,
            "company": getattr(j.company, "name", ""),
            "city": getattr(j.city, "name", ""),
            "salary": j.money,
            "experience": j.get_working_display(),
            "education": j.education,
            "label": j.label,
        })
    import json
    return json.dumps({"jobs": items}, ensure_ascii=False)


def build_job_tools():
    return [JobSearch]


